const db = uniCloud.databaseForJQL()
import {
	shopIcon
} from "../shopIcon";


/**
 * 添加地图标记（用户、商铺、收藏点）
 * @param {Object} storeData 全局变量（包含用户信息、位置等）
 * @returns {Array} 整理后的标记数组
 */
export async function addMarker(storeData, Region, vm) {

	const {
		southwest,
		northeast
	} = Region;

	// 1. 转换经纬度并保留精度
	const swLng = Number(southwest.longitude);
	const swLat = Number(southwest.latitude);
	const neLng = Number(northeast.longitude);
	const neLat = Number(northeast.latitude);
	// 容错：检查storeData及必要属性是否存在

	if (!storeData || !storeData.user || !storeData.location) {
		console.error('addMarker失败：storeData缺少必要属性');
		return [];
	}

	let markers = [];

	// 添加当前用户标记
	const currentUserMarker = {
		keytag: '普通用户',
		type: '普通用户',
		id: storeData.user.userId,
		latitude: storeData.location.latitude,
		longitude: storeData.location.longitude,
		iconPath: storeData.user.nicPic.url || '@/static/nicPic/m1.png', // 兜底默认头像
		width: 40,
		height: 40,
		zIndex: 1,

		label: {
			color: '#666666',
			borderWidth: 3,
			borderRadius: 5,
			anchorX: 0,
			textAlign: "center",
			anchorX: anchor(storeData.user.nicName || '本人'),
			anchorY: 0,
			padding: 5,
			bgColor: 'rgba(255,255,255,0.5)',
			content: storeData.user.nicName || '本人',
			fontSize: 18,

		}
	};

	// 添加当前用户标记
	try {
		// 获取周边用户
		const event = {
			type: "getNearByInfo",
			location: storeData.location,
			radius: storeData.stateConfig.radius || 5 // 兜底默认半径
		};
		const res = await uniCloud.callFunction({
			name: 'web',
			data: event
		});
		console.log("用户。。。。。。",res);
		const userMarkers = res.result.data
			.map(item => { // 1. 先提取用户信息，兜底空对象（避免item.userId[0]为undefined）
			
				const rawNickName = item.nicName || item.userId
				// 3. 安全调用replace：用空字符串兜底，避免rawNickName意外为undefined
				const processedNickName = (rawNickName + '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')
					.substring(0, 5);

				return {
					id: item.userId, // 优化：id兜底，避免重复
					keytag: '普通用户',
					type: '普通用户',
					// 坐标容错：确保coordinates存在且为数组，否则用当前用户坐标兜底
					latitude: item.location.latitude,
					longitude: item.location.longitude,
					iconPath: item.nicPic?.url || '@/static/nicPic/m1.png', // 优化：nicPic可能为undefined，加?+默认图
					width: 30,
					height: 30,
					label: {
						color: '#666666',
						borderWidth: 3,
						borderRadius: 5,
						anchorX: anchor(processedNickName), // 修复：原代码重复定义anchorX，删除冗余项
						anchorY: 0,
						padding: 5,
						bgColor: 'rgba(255,255,255,0.5)',
						content: processedNickName, // 使用提前处理好的昵称，避免直接链式调用
						fontSize: 16,
						textAlign: "center"
					}
				};
			});

		// 并行获取商铺和收藏点标记，提高性能
		const [shops, favorites] = await Promise.all([
			handlerShopShow(storeData),
			getFavorites(storeData)
		]);


		markers = [...userMarkers, ...shops, ...favorites, currentUserMarker]; //

	} catch (error) {
		console.error('获取标记数据失败:', error);
	}

	return markers.filter(item => item.longitude > swLng && item.longitude < neLng && item.latitude > swLat && item
		.latitude < neLat)
}

function anchor(word) {
	const fontSize = 16
	return -(word.length * fontSize / 2)

}
/**
 * 处理商铺标记显示
 * @param {Object} storeData 全局变量
 * @returns {Array} 商铺标记数组
 */
async function handlerShopShow(storeData) {
	// 建议：从地图实例获取实际缩放级别，这里暂时保留默认值


	try {
		const pipeline = await db
			.collection('sendshop')
			.aggregate()
			.geoNear({
				distanceField: 'distance',
				spherical: true,
				near: new db.Geo.Point(
					storeData.location.longitude,
					storeData.location.latitude
				),
				maxDistance: storeData.user.receiveDistance || 500 // 默认值兜底
			})
			.limit(500)
			.end();

		return (pipeline.data || []).map(item => {
			const baseIcon = shopIcon(item.category) || {};
			const markerBase = {
				id: item.sendshopId,
				type: '商业',
				keytag: item.category,
				latitude: item.location?.coordinates?.[1] ?? storeData.location.latitude,
				longitude: item.location?.coordinates?.[0] ?? storeData.location.longitude,
				iconPath: baseIcon?.url || '/static/shoping.png',
				joinCluster: storeData.user.stateConfig.joinCluster,
				width: 30,
				height: 30,
				label: {
					color: '#fff',
					borderWidth: 1,
					borderRadius: 5,
					anchorX: -36,
					anchorY: 0,
					padding: 5,
					bgColor: baseIcon.color || '#000',
					content: (item.title || '').replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '').substring(0,
						5),
					fontSize: 16,

				}
			};


			return markerBase;


		});

	} catch (error) {
		console.error('获取商铺数据失败:', error);
		return [];
	}
}

/**
 * 获取收藏点标记
 * @param {Object} storeData 全局变量
 * @returns {Array} 收藏点标记数组
 */
async function getFavorites(storeData) {
	// 容错：确保用户收藏是数组
	const userFavorites = Array.isArray(storeData.user.favorite) ? storeData.user.favorite : [];

	return userFavorites
		.filter(favorite => favorite.type === 'location' && favorite.location)
		.map(favorite => ({
			id: favorite.favorite_id,
			keytag: "收藏点",
			type: "收藏点",
			latitude: favorite.location.latitude,
			longitude: favorite.location.longitude,
			iconPath: "/static/loved.png",
			width: 40,
			height: 40,
			label: {
				color: '#fff',
				borderWidth: 1,
				borderRadius: 5,
				anchorX: -36,
				anchorY: 0,
				padding: 5,
				bgColor: '#ff557f',
				content: (favorite.name.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '').substring(0, 5) || ''),
				fontSize: 16,

			},
			joinCluster: storeData.user.stateConfig.joinCluster
		}));
}